<?php
class check_in_log extends CI_Model
{
    public $id;
    public $ticket_number;
    public $check_count;
    public $created_date;

    public function get_elements()
    {
        $query = $this->db->query("SELECT * FROM check_in_log");
        return $query->result();
    }

    public function get_element_by_id($id)
    {
        $query = $this->db->query("SELECT * FROM check_in_log WHERE id = ?",array($id));
        return $query->row();
    }

    public function get_element_by_ticket_number($id)
    {
        $query = $this->db->query("SELECT * FROM check_in_log WHERE ticket_number = ?",array($id));
        return $this->to_domain_model($query->row());
    }

    public function log_by_ticket_number($ticket_number){
        $log_item = $this->get_element_by_ticket_number($ticket_number);
        if($log_item->id != ''){
            $log_item->check_count++;
            $data = array(
                'id' => $log_item->id,
                'ticket_number' => $log_item->ticket_number,
                'check_count' => $log_item->check_count
            );

            return $this->update($data);
        }else{
            $data = array(
                'ticket_number' => $ticket_number,
                'check_count' => '1'
            );
            return $this->insert_new($data);
        }
    }

    public function get_wrong_number(){
        $query = $this->db->query("SELECT SUM(check_count) AS sumCount FROM check_in_log");
        return $query->row();
    }


    public function insert_new($data){
        $insert_id = -1;
        $this->db->insert('check_in_log',$data);
        $insert_id = $this->db->insert_id();
        if($insert_id != -1){
            return true;
        }
        return false;
    }

    public function update($data){
        $this->db->where('id',$data['id']);
        $this->db->update('check_in_log',$data);
        return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
    }

    public function get_count_by_ticket_number($ticket_number){
        $query = $this->db->query("SELECT count(*) FROM check_in_log WHERE ticket_number = ?",array($ticket_number));
        return $query->count();
    }

    public function get_count_wrong_check_in(){
        $query = $this->db->query("SELECT count(DISTINCT ticket_number) FROM check_in_log");
        return $query->count();
    }

    public function to_domain_model($item)
    {
        $model = new check_in_log();
        $model->id = isset($item->id) ? $item->id : '' ;
        $model->ticket_number = isset($item->ticket_number) ? $item->ticket_number : '' ;
        $model->check_count = isset($item->check_count) ? $item->check_count : '' ;
        $model->created_date = isset($item->created_date) ? $item->created_date : '' ;
        return $model;
    }
}